<template>
  <div class="chat-container">
    <h1>教师聊天</h1>

    <div class="user-info">
      <p>欢迎，{{ userProfile.fullName }} 老师</p>
      <router-link to="/teacher/dashboard">返回Dashboard</router-link>
    </div>

    <div class="chat-main">
      <div class="contacts-section">
        <h2>联系人</h2>
        <div class="class-selector">
          <label for="class-select">选择班级:</label>
          <select id="class-select" v-model="selectedClassId" @change="loadContacts">
            <option value="">请选择班级</option>
            <option v-for="cls in teachingClasses" :key="cls.id" :value="cls.id">
              {{ cls.className }}
            </option>
          </select>
        </div>

        <div class="search-section">
          <input type="text" v-model="studentName" placeholder="学生姓名" class="search-input">
          <input type="text" v-model="studentNumber" placeholder="学生学号" class="search-input">
          <button @click="loadContacts" class="search-btn">查询</button>
          <button @click="clearSearch" class="clear-btn">清除</button>
        </div>

        <div class="contacts-list">
          <div
              v-for="contact in contacts"
              :key="contact.userId"
              class="contact-item"
              :class="{ active: activeContact && activeContact.userId === contact.userId }"
              @click="selectContact(contact)"
          >
            <div class="contact-avatar">
              {{ contact.fullName.charAt(0) }}
            </div>
            <div class="contact-info">
              <div class="contact-name">
                <span v-if="contact.userType === '1' ">
                  {{ contact.subejt }} - {{ contact.fullName }}
                </span>
                <span v-else>
                  {{ contact.fullName }}
                </span>
              </div>
              <div class="contact-type">{{ getUserTypeText(contact.userType) }}</div>
            </div>
            <div v-if="unreadCounts[contact.userId] && unreadCounts[contact.userId] > 0" class="unread-badge">
              {{ unreadCounts[contact.userId] }}
            </div>
          </div>

          <div v-if="contacts.length === 0 && selectedClassId" class="no-contacts">
            暂无联系人
          </div>
        </div>
      </div>

      <div class="chat-section">
        <div v-if="activeContact" class="chat-header">
          <h3>
            与
            <span v-if="activeContact.userType === '1' && activeContact.subejt">
              {{ activeContact.subejt }} - {{ activeContact.fullName }}
            </span>
            <span v-else>
              {{ activeContact.fullName }}
            </span>
            聊天
          </h3>
          <button @click="loadChatHistory" class="refresh-btn">刷新</button>
        </div>
        <div v-else class="chat-placeholder">
          <p>请选择一个联系人开始聊天</p>
        </div>

        <div v-if="activeContact" class="chat-messages" ref="messagesContainer">
          <div
              v-for="message in messages"
              :key="message.id"
              class="message"
              :class="{ 'sent': String(message.senderId) === String(userProfile.userId), 'received': String(message.senderId) !== String(userProfile.userId) }"
          >
            <div class="message-content">
              {{ message.content }}
            </div>
            <div class="message-time">
              {{ formatDateTime(message.sentAt) }}
            </div>
          </div>
        </div>

        <div v-if="activeContact" class="chat-input">
          <textarea
              v-model="newMessage"
              placeholder="输入消息..."
              @keydown.enter="sendMessage"
          ></textarea>
          <button @click="sendMessage" :disabled="!newMessage.trim()">发送</button>
        </div>
      </div>
    </div>

    <div v-if="error" class="error-message">
      {{ error }}
    </div>

    <div v-if="success" class="success-message">
      {{ success }}
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, nextTick } from 'vue';

export default {
  name: 'TeacherChat',
  setup() {
    // 用户信息
    const userProfile = ref({});

    // 班级和联系人
    const teachingClasses = ref([]);
    const selectedClassId = ref('');
    const contacts = ref([]);
    const activeContact = ref(null);

    // 新增：搜索条件
    const studentName = ref('');
    const studentNumber = ref('');

    // 消息
    const messages = ref([]);
    const newMessage = ref('');
    const messagesContainer = ref(null);
    const unreadCounts = ref({}); // 未读消息计数

    // 定时器
    let messageRefreshTimer = null;
    let unreadCountTimer = null;

    // 状态信息
    const error = ref('');
    const success = ref('');

    // 获取用户信息
    const loadUserProfile = async () => {
      try {
        const response = await fetch('/user/profile', {
          method: 'GET',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json',
            'Cache-Control': 'no-cache',
            'Pragma': 'no-cache',
            'Expires': '0'
          }
        });

        const result = await response.json();
        if (result.code === 1) {
          userProfile.value = result.data;
          await loadTeachingClasses();
          startUnreadCountRefresh();
        } else {
          error.value = result.msg || '获取用户信息失败';
        }
      } catch (err) {
        error.value = '网络错误，请稍后重试';
      }
    };

    // 获取授课班级
    const loadTeachingClasses = async () => {
      try {
        const response = await fetch('/teacher/classes', {
          method: 'GET',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json',
            'Cache-Control': 'no-cache',
            'Pragma': 'no-cache',
            'Expires': '0'
          }
        });

        const result = await response.json();
        if (result.code === 1) {
          teachingClasses.value = result.data;
        } else {
          error.value = result.msg || '获取授课班级失败';
        }
      } catch (err) {
        error.value = '网络错误，请稍后重试';
      }
    };

    // 更新：加载联系人方法
    const loadContacts = async () => {
      if (!selectedClassId.value) {
        contacts.value = [];
        return;
      }

      try {
        // 构建带查询参数的URL
        let url = `/chat/teacher/contacts?classId=${selectedClassId.value}`;
        if (studentName.value) {
          url += `&studentName=${encodeURIComponent(studentName.value)}`;
        }
        if (studentNumber.value) {
          url += `&studentNumber=${encodeURIComponent(studentNumber.value)}`;
        }

        const response = await fetch(url, {
          method: 'GET',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json',
            'Cache-Control': 'no-cache',
            'Pragma': 'no-cache',
            'Expires': '0'
          }
        });

        const result = await response.json();

        if (result.code === 1) {
          contacts.value = result.data;
          if (activeContact.value && !contacts.value.some(c => c.userId === activeContact.value.userId)) {
            activeContact.value = null;
            messages.value = [];
          }
          await loadUnreadCounts();
        } else {
          error.value = result.msg || '获取联系人失败';
        }
      } catch (err) {
        console.error('Load contacts error:', err);
        error.value = '网络错误，请稍后重试: ' + err.message;
      }
    };

    // 新增：清除搜索条件的方法
    const clearSearch = () => {
      studentName.value = '';
      studentNumber.value = '';
      loadContacts();
    };

    // 选择联系人
    const selectContact = async (contact) => {
      activeContact.value = contact;
      await loadChatHistory();
      scrollToBottom();
      await markMessagesAsRead(contact.userId);
      startMessageRefresh();
    };

    // 加载聊天历史
    const loadChatHistory = async () => {
      if (!activeContact.value) return;
      try {
        const response = await fetch(`/chat/history?contactId=${activeContact.value.userId}&page=0&size=50`, {
          method: 'GET',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json',
            'Cache-Control': 'no-cache',
            'Pragma': 'no-cache',
            'Expires': '0'
          }
        });
        const result = await response.json();
        if (result.code === 1) {
          messages.value = result.data;
          await nextTick();
          scrollToBottom();
        } else {
          error.value = result.msg || '获取聊天记录失败';
        }
      } catch (err) {
        error.value = '网络错误，请稍后重试';
      }
    };

    // 发送消息
    const sendMessage = async (e) => {
      if (e && e.shiftKey) return;
      if (e) e.preventDefault();
      if (!newMessage.value.trim() || !activeContact.value) return;

      try {
        const response = await fetch(`/chat/send?recipientId=${activeContact.value.userId}&content=${encodeURIComponent(newMessage.value)}`, {
          method: 'POST',
          credentials: 'include',
          headers: { 'Content-Type': 'application/json' }
        });
        const result = await response.json();
        if (result.code === 1) {
          messages.value.push(result.data);
          newMessage.value = '';
          await nextTick();
          scrollToBottom();
        } else {
          error.value = result.msg || '发送消息失败';
        }
      } catch (err) {
        error.value = '网络错误，请稍后重试';
      }
    };

    // 标记消息为已读
    const markMessagesAsRead = async (senderId) => {
      try {
        await fetch(`/chat/mark-as-read?senderId=${senderId}`, {
          method: 'POST',
          credentials: 'include',
          headers: { 'Content-Type': 'application/json' }
        });
        await loadUnreadCounts();
      } catch (err) {
        console.error('标记消息为已读失败:', err);
      }
    };

    // 加载未读消息数
    const loadUnreadCounts = async () => {
      try {
        if (contacts.value.length === 0) return;
        const contactIds = contacts.value.map(contact => contact.userId);
        const response = await fetch('/chat/unread-count-by-contacts', {
          method: 'POST',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json',
            'Cache-Control': 'no-cache',
            'Pragma': 'no-cache',
            'Expires': '0'
          },
          body: JSON.stringify(contactIds)
        });
        const result = await response.json();
        if (result.code === 1) {
          unreadCounts.value = result.data;
        } else {
          console.error('获取未读消息数失败:', result.msg);
        }
      } catch (err) {
        console.error('获取未读消息数失败:', err);
      }
    };

    // 滚动到底部
    const scrollToBottom = () => {
      if (messagesContainer.value) {
        messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
      }
    };

    // 定时刷新
    const startMessageRefresh = () => {
      if (messageRefreshTimer) clearInterval(messageRefreshTimer);
      messageRefreshTimer = setInterval(() => {
        if (activeContact.value) loadChatHistory();
      }, 10000);
    };
    const startUnreadCountRefresh = () => {
      if (unreadCountTimer) clearInterval(unreadCountTimer);
      unreadCountTimer = setInterval(loadUnreadCounts, 30000);
    };
    const stopMessageRefresh = () => {
      if (messageRefreshTimer) {
        clearInterval(messageRefreshTimer);
        messageRefreshTimer = null;
      }
    };
    const stopUnreadCountRefresh = () => {
      if (unreadCountTimer) {
        clearInterval(unreadCountTimer);
        unreadCountTimer = null;
      }
    };

    // 格式化日期
    const formatDateTime = (dateTimeString) => {
      if (!dateTimeString) return '';
      return new Date(dateTimeString).toLocaleString('zh-CN');
    };

    // 获取用户类型文本
    const getUserTypeText = (userType) => {
      switch (userType) {
        case '1': return '老师';
        case '2': return '学生';
        case '3': return '家长';
        default: return '未知';
      }
    };

    // 初始化和卸载
    onMounted(async () => {
      await loadUserProfile();
    });
    onUnmounted(() => {
      stopMessageRefresh();
      stopUnreadCountRefresh();
    });

    return {
      userProfile,
      teachingClasses,
      selectedClassId,
      contacts,
      activeContact,
      studentName,
      studentNumber,
      messages,
      newMessage,
      messagesContainer,
      unreadCounts,
      error,
      success,
      loadContacts,
      clearSearch,
      selectContact,
      loadChatHistory,
      sendMessage,
      formatDateTime,
      getUserTypeText
    };
  }
};
</script>

<style scoped>
/* 基本样式 */
.chat-container { max-width: 1200px; margin: 0 auto; padding: 20px; font-family: Arial, sans-serif; }
.user-info { background-color: #f5f5f5; padding: 15px; border-radius: 5px; margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center; }
.user-info a { color: #409EFF; text-decoration: none; padding: 5px 10px; border: 1px solid #409EFF; border-radius: 4px; transition: all 0.3s; }
.user-info a:hover { background-color: #409EFF; color: white; }
.chat-main { display: flex; gap: 20px; height: 70vh; }
.contacts-section { flex: 1; background-color: #fff; border: 1px solid #ddd; border-radius: 5px; padding: 20px; display: flex; flex-direction: column; }
.contacts-section h2 { margin-top: 0; }
.class-selector { margin-bottom: 15px; display: flex; align-items: center; gap: 10px; }
.class-selector label { font-weight: bold; }
.class-selector select { flex: 1; padding: 8px; border: 1px solid #ddd; border-radius: 4px; }

/* 新增搜索区域样式 */
.search-section {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  align-items: center;
}
.search-input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}
.search-btn, .clear-btn {
  padding: 8px 15px;
  border: none;
  border-radius: 4px;
  color: white;
  cursor: pointer;
  transition: background-color 0.3s;
}
.search-btn {
  background-color: #409EFF;
}
.search-btn:hover {
  background-color: #3a8ee6;
}
.clear-btn {
  background-color: #909399;
}
.clear-btn:hover {
  background-color: #82848a;
}

/* 联系人列表 */
.contacts-list { flex: 1; overflow-y: auto; }
.contact-item { display: flex; align-items: center; padding: 10px; border-bottom: 1px solid #eee; cursor: pointer; transition: background-color 0.2s; position: relative; }
.contact-item:hover { background-color: #f5f5f5; }
.contact-item.active { background-color: #e3f2fd; }
.contact-avatar { width: 40px; height: 40px; border-radius: 50%; background-color: #409EFF; color: white; display: flex; align-items: center; justify-content: center; font-weight: bold; margin-right: 10px; }
.contact-info { flex: 1; }
.contact-name { font-weight: bold; }
.contact-type { font-size: 12px; color: #666; }
.unread-badge { background-color: #f44336; color: white; border-radius: 50%; width: 20px; height: 20px; display: flex; align-items: center; justify-content: center; font-size: 12px; font-weight: bold; }
.no-contacts { text-align: center; color: #999; padding: 20px; }

/* 聊天窗口 */
.chat-section { flex: 2; display: flex; flex-direction: column; background-color: #fff; border: 1px solid #ddd; border-radius: 5px; padding: 20px; }
.chat-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; }
.chat-header h3 { margin: 0; }
.refresh-btn { padding: 5px 10px; background-color: #9E9E9E; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 14px; }
.refresh-btn:hover { background-color: #7a7a7a; }
.chat-placeholder { flex: 1; display: flex; align-items: center; justify-content: center; color: #999; }
.chat-messages { flex: 1; overflow-y: auto; padding: 10px; border: 1px solid #eee; border-radius: 4px; margin-bottom: 15px; display: flex; flex-direction: column; }
.message { max-width: 70%; padding: 10px; margin-bottom: 10px; border-radius: 10px; }
.message.sent { align-self: flex-end; background-color: #409EFF; color: white; }
.message.received { align-self: flex-start; background-color: #f5f5f5; }
.message-content { margin-bottom: 5px; word-wrap: break-word; }
.message-time { font-size: 12px; opacity: 0.8; }
.chat-input { display: flex; gap: 10px; }
.chat-input textarea { flex: 1; padding: 10px; border: 1px solid #ddd; border-radius: 4px; resize: none; height: 60px; }
.chat-input button { padding: 10px 20px; background-color: #409EFF; color: white; border: none; border-radius: 4px; cursor: pointer; }
.chat-input button:disabled { background-color: #ccc; cursor: not-allowed; }

/* 提示信息 */
.error-message { background-color: #f8d7da; color: #721c24; padding: 15px; border-radius: 5px; margin-top: 20px; }
.success-message { background-color: #d4edda; color: #155724; padding: 15px; border-radius: 5px; margin-top: 20px; }
</style>